from django.db import models
from django.contrib.auth.models import User
from django import forms
from django.template.defaultfilters import slugify
from django.shortcuts import Http404

from apps.additions import AllowAdditions
from apps.course.models import Course, CourseForm
import logging

logger = logging.getLogger('pet.apps.participants.models')

AllowAdditions(User)

def find(username):
	logger.find_fxn('username %s',username)
	Objects = User.objects.filter(username=username)
	if Objects: return Objects[0]
	return None
def find_or_404(username):
	Result = User.find(username)
	if not Result:
		logger.http404('User %s not found',username,display_caller=True)
		raise Http404
	return Result
User.add_to_class('find',staticmethod(find))
User.add_to_class('find_or_404',staticmethod(find_or_404))
User.add_to_class('allow_student_file_upload',True)

class MultiUserUploadForm(forms.Form):
	SEPARATORS = (
		('\t','Tab (    )'),
		(',','Comma (,)'),
		(';','Semicolon (;)'),
		(' ','Space ( )'),
		('OTHER','Other - Enter in the box below')
	)
	NAMES = (
		('Same','Same Column'),
		('SeparateLastFirst','Separate Columns - Last name then First name'),
		('SeparateFirstLast','Separate Columns - First name then Last name'),
	)
	data = forms.CharField(widget=forms.Textarea(attrs={'class':'mceNoEditor'}),required=False,
			help_text="""Copy and paste spreadsheet data here. <br>Example Spreadsheet:<br>
			<table border='1' style="width:1px;"><tr><th>Last</th><th>First</th><th>Username</th><th>Email</th></tr>
			<tr><td>Mason</td><td>Barbara</td><td>bmason</td><td>bmason@somewhere.edu</td></tr>
			<tr><td>Reiber</td><td>Monty</td><td>mreiber</td><td>mreiber@somewhere.edu</td></tr>
			<tr><td>Harvey</td><td>Tami</td><td>tharvey</td><td>something.crazy@gmail.com</td></tr>
			</table>""")
	headers_included = forms.BooleanField(initial=True,required=False,help_text="If headers are not included, only name and email address (in that order) will be used")
	email_users = forms.BooleanField(initial=False,required=False,help_text="""If selected, new users will be emailed 
		their usernames and initial passwords. Note: This is very insecure. 
		Only check this if you have a way to verify that the correct user is using the account""")
	name_format = forms.ChoiceField(choices=NAMES,help_text="If headers are not included, this indicates how names are formatted in your data")
	separator = forms.ChoiceField(choices=SEPARATORS)
	other_separator = forms.CharField(required=False)
	
class UserForm(forms.ModelForm):
	class Meta:
		model = User
		fields = ['first_name', 'last_name', 'email']

class ManagementUserForm(forms.ModelForm):
	email_users = forms.BooleanField(initial=False,required=False,help_text="""If selected, new users will be emailed 
		their usernames and initial passwords. Note: This is very insecure. 
		Only check this if you have a way to verify that the correct user is using the account""")
	class Meta:
		model = User
		fields = ['first_name', 'last_name', 'username', 'email']
		
class CourseParticipant(models.Model):
	"""
	Multiple participants can be associated with multiple classes where each relationship is represented by one CourseParticipant object.
	
	This gets around the ManyToMany limitation in djangoappengine for GAE.
	"""
	DEFAULT_CHOICES = (
			('INSTRUCTOR',"Instructor"),
			('ASSISTANT',"Assistant"),
			('STUDENT',"Student"),
			)
	user = models.ForeignKey(User)
	course = models.ForeignKey(Course)
	status = models.CharField(max_length=15, choices=DEFAULT_CHOICES, default=DEFAULT_CHOICES[2][0])

	def __unicode__(self):
		return "%s - %s" % (self.course, self.user)
	def is_instructor(self):
		return self.status == "INSTRUCTOR"
	def is_assistant(self):
		return self.status == "ASSISTANT"
	def is_student(self):
		return self.status == "STUDENT"
	def username(self):
		return self.user.username
	def first_name(self):
		return self.user.first_name
	def last_name(self):
		return self.user.last_name
	def email(self):
		return self.user.email
	def is_staff(self):
		return self.user.is_staff
	def is_superuser(self):
		return self.user.is_superuser
	def is_active(self):
		return self.user.is_active
	def last_login(self):
		return self.user.last_login
	def date_joined(self):
		return self.user.date_joined
	
	@staticmethod
	def find(course=None, user=None, status=None, id=None, keep_queryset=False):
		logger.find_fxn("course=%s, user=%s, status=%s, id=%s, keep_queryset=%s",course,user,status,id,keep_queryset)
		if user and not user.is_authenticated(): logger.debug("User is not authenticated. Returning no CourseParticipant"); return None
		Objects = CourseParticipant.objects.all()
		if course:
			if not isinstance(course,Course):
				course = Course.find_or_404(course_id=course)
			Objects = Objects.filter(course=course)
		if user: Objects = Objects.filter(user=user)
		if status: Objects = Objects.filter(status=status)
		if id: Objects = Objects.filter(id=id)
		if Objects:
			def participant_sort(user):
				if user.status == "INSTRUCTOR": Order = 1;
				elif user.status == "ASSISTANT": Order = 2;
				else: Order = 3;
				return "%d %s %s" % (Order,user.user.last_name,user.user.first_name)
			if (user or id) and not keep_queryset: return Objects[0]
			if not keep_queryset: Objects = sorted(Objects,key=participant_sort)
			return Objects
		return None
	@staticmethod
	def find_or_404(course=None, user=None, status=None):
		Result = CourseParticipant.find(course, user, status)
		if not Result:
			logger.http404('CourseParticipant for user %s in course %s not found',user,course,display_caller=True)
			raise Http404
		return Result
	class Meta:
		unique_together = ('user','course')
		
class CourseParticipantForm(forms.ModelForm):
	def get_choices(self):
		from options import Options
		return (
			('INSTRUCTOR',Options.get_option("Instructor Status Title","Instructors","Participants")),
			('ASSISTANT',Options.get_option("Assistant Status Title","Assistants","Participants")),
			('STUDENT',Options.get_option("Student Status Title","Students","Participants")),
			)
		
	def __init__(self, *args, **kwargs):
		super(CourseParticipantForm, self).__init__(*args, **kwargs)
		self.fields['status'].choices = self.get_choices()
	class Meta:
		model = CourseParticipant
		fields = ['course','status']
